package u1project.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import u1project.common.Request;
import u1project.common.Response;

import java.io.*;

//处理客户端（C）和网络相关的操作
public class ClientSocket {
	private String ip = "localhost";
	private int port = 6666;

	private Socket client;

	private ObjectInputStream oin;
	private ObjectOutputStream oout;

	public ClientSocket() {
	}

	public ClientSocket(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	public void start() {
		try {
			client = new Socket(ip, port);
			oout = new ObjectOutputStream(client.getOutputStream());
			oin = new ObjectInputStream(client.getInputStream());

		} catch (Exception e) {
			System.out.println("连接失败！");
			e.printStackTrace();
		}
	}

	// 发送和接收
	public Response send(Request req) {
		try {
			oout.writeObject(req);
			oout.flush();
			oout.reset();
			return (Response) oin.readObject();
		} catch (Exception e) {

			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public void close() {
		try {
			client.close();
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}
}
